﻿namespace JUpload.Net
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.ComponentModel;
    using System.IO;

    /// <summary>
    /// The JUpload control encapsulates the JUpload applet, the output is simply an "applet" tag.
    /// Not all of the options of the applet are covered.
    /// </summary>
    [ToolboxData("<{0}:JUpload runat=server></{0}:JUpload>")]
    [Designer(typeof(JUploadDesigner))]
    public class JUpload : System.Web.UI.WebControls.WebControl
    {
        // Fields
        private string uploadHandlerUrl;

        /// <summary>
        /// The url for the upload handler. The upload handler is tipically
        /// an http handler wich delegates the handling of jupload requests.
        /// </summary>
        public string UploadHandlerUrl
        {
            set
            {
                uploadHandlerUrl = value;
            }
        }

        /// <summary>
        /// The list of uploaded files
        /// </summary>
        public List<UploadedFile> UploadedFiles { get; set; }

        public string AfterUploadUrl { get; set; }

        /// <summary>
        /// true if the control has uploaded almost 1 file in this request
        /// </summary>
        public bool HasFiles
        {
            get
            {
                return UploadedFiles != null && UploadedFiles.Count > 0;
            }
        }

        /// <summary>
        /// Gets/sets the directory where is placed the applet. If not set, will be used the applet stored in the assembly
        /// </summary>
        public string AppletLocation { get; set; }

        /// <summary>
        /// Event raised when has occurred the last upload
        /// </summary>
        public event EventHandler Upload;

        /// <summary>
        /// Saves all the files in the folder specified by the user
        /// </summary>
        /// <param name="folder"></param>
        public void SaveAllFilesToFolder(string folder)
        {
            foreach (UploadedFile uf in UploadedFiles)
            {
                string filePath = folder + "/" + uf.FileName; 

                BinaryReader br = new BinaryReader(uf.FileStream);
                BinaryWriter sw = new BinaryWriter(new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write));
                
                sw.Write(br.ReadBytes((int)uf.FileStream.Length));
                
                sw.Close();
                br.Close();
            }
        }

        private bool callUpload;

        /// <summary>
        /// Overrides the User Control's Init Event.
        /// Manages the retrieval of the uploaded files from the cache and cleans the cache.
        /// Raises the Upload event.
        /// </summary>
        /// <param name="e">Event arguments</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            //Page.ClientScript.RegisterClientScriptResource(this.GetType(), 
            callUpload = false;
            int? JUploadFilesCount = (int?)this.Context.Cache["JUploadFilesCount"];
            if (JUploadFilesCount != null && JUploadFilesCount > 0)
            {
                UploadedFiles = (List<UploadedFile>)Context.Cache["JUploadUploadedFiles"];

                Context.Cache.Remove("JUploadUploadedFiles");
                Context.Cache.Remove("JUploadFilesCount");
                Context.Cache.Insert("JUploadFilesCount", 0);

                callUpload = true;
                
            }
            else
            {
                Context.Cache.Remove("JUploadUploadedFiles");
                Context.Cache.Remove("JUploadFilesCount");
                Context.Cache.Insert("JUploadFilesCount", 0);
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (callUpload && Upload != null)
            {
                Upload(this, new EventArgs());
            }
        }

        /// <summary>
        /// Renders the control to the specified HtmlTextWriter
        /// </summary>
        /// <param name="output">The HtmlTextWriter that receives the control's content</param>
        protected override void Render(HtmlTextWriter output)
        {
            //http://www.karpach.com/Custom-ASP-NET-server-control-with-embedded-resources.htm
            //http://www.aspitalia.com/focuson/996/Speciale-Custom-Control-ASP.NET.aspx
            //http://jupload.sourceforge.net/howto-customization.html#parameters

            string jars = "Applet/wjhk.jupload.jar";
//            string jars = @"Applet/wjhk.jupload.jar,Applet/commons-codec-1.3.jar,
//				Applet/commons-httpclient-3.0-rc4.jar,
//				Applet/commons-logging.jar";

            //wjhk.jupload2.JUploadApplet
            string ftext = @"<applet code=""wjhk.jupload2.JUploadApplet""
	        name=""JUpload""
	        mayscript
	        archive=""{0}""
            formdata={3}
	        width=""640""
	        height=""300""
            afterUploadURL=""{1}""
	        alt=""The java pugin must be installed."">
            <!-- param name=""CODE""    value=""wjhk.jupload2.JUploadApplet"" / -->
            <!-- param name=""ARCHIVE"" value=""wjhk.jupload.jar"" / -->
            <!-- param name=""type""    value=""application/x-java-applet;version=1.5"" /  -->
            <param name=""postURL"" value=""{2}"" />
            <param name=""scriptable"" value=""true""> 
            <!-- Optionnal, see code comments -->
            <param name=""showLogWindow"" value=""false"" />
            Java 1.5 or higher plugin required. 
        </applet>";

            string appletUrl;

            if (!string.IsNullOrEmpty(AppletLocation))
            {
                appletUrl = Page.ResolveUrl(AppletLocation) + "/wjhk.jupload.jar";
            }
            else
            {
                appletUrl = Page.ClientScript.GetWebResourceUrl(typeof(JUpload), "JUpload.Net.Applet.wjhk.jupload.jar");
            }

            //Page.ClientScript.RegisterStartupScript(this.GetType(), "jsRegisterUploaded", "function myUploaded() { alert('foo'); } ;$(document).ready(function(){ document.JUpload.js().RegisterUploaded('myUploaded'); });", true);
            

            string uplHandler = string.IsNullOrEmpty(uploadHandlerUrl) ? "JUploadDotNetUploadHandler.ashx" : uploadHandlerUrl; // Page.Request.Url.PathAndQuery

            //string afterUploadUrl = string.IsNullOrEmpty(AfterUploadUrl) ? Page.Request.Url.PathAndQuery : Page.ResolveUrl(AfterUploadUrl);
            string afterUploadUrl = string.IsNullOrEmpty(AfterUploadUrl) ? Page.ClientScript.GetPostBackClientHyperlink(this, "") : Page.ResolveUrl(AfterUploadUrl);
            
            //output.Write(string.Format(ftext, Page.ClientScript.GetWebResourceUrl(typeof(JUpload), "wjhk.jupload.jar")));
            output.Write(string.Format(ftext, appletUrl, afterUploadUrl, uplHandler, Page.Form.ClientID));
        }
    }
}
